import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

class LYWeekDate {
  final DateTime start;
  final DateTime end;
  String description = "";
  final dateFormat = DateFormat("yyyy年MM月dd日");
  LYWeekDate({required this.start, required this.end}) {
    description = "${dateFormat.format(start)}-${dateFormat.format(end)}";
  }
  static LYWeekDate current() {
    DateTime now = DateTime.now();
    final startOfWeek = getStartOfWeek(now);
    final endOfWeek = getEndOfWeek(now);
    return LYWeekDate(start: startOfWeek, end: endOfWeek);
  }
}

// 获取给定日期所在周的开始日期（周一）
DateTime getStartOfWeek(DateTime date) {
  return date.subtract(Duration(days: date.weekday - 1));
}

// 获取给定日期所在周的结束日期（周日）
DateTime getEndOfWeek(DateTime date) {
  return date.add(Duration(days: DateTime.daysPerWeek - date.weekday));
}

class LYWeekPicker extends StatefulWidget {
  final String? title;
  final List<LYWeekDate> dataList;
  final LYWeekDate? weekDate;
  final int maxWeekNumber;
  final Function(LYWeekDate)? onChanged;
  final Function(LYWeekDate)? onConfirm;
  const LYWeekPicker(
      {super.key,
      this.dataList = const [],
      this.title,
      this.onChanged,
      this.onConfirm,
      this.weekDate,
      this.maxWeekNumber = 100});

  static void show(
      {List<LYWeekDate> dataList = const [],
      LYWeekDate? weekDate,
      Function(LYWeekDate)? onChanged,
      Function(LYWeekDate)? onConfirm}) {
    Get.dialog(LYWeekPicker(
      dataList: dataList,
      onChanged: onChanged,
      onConfirm: onConfirm,
      weekDate: weekDate,
    ));
  }

  @override
  State<LYWeekPicker> createState() => _GroupSelectorState();
}

class _GroupSelectorState extends State<LYWeekPicker> {
  late FixedExtentScrollController controller;
  late LYWeekDate weekDate;
  List<LYWeekDate> weekList = [];

  @override
  void initState() {
    super.initState();
    initData();
  }

  void initData() async {
    if (widget.dataList.isNotEmpty) {
      weekList = widget.dataList;
    } else {
      weekList = await makeWeekData();
    }
    weekDate = widget.weekDate ?? weekList.first;
    final index = weekList.indexWhere((e) => e.description == weekDate.description);
    controller = FixedExtentScrollController(initialItem: index != -1 ? index : 0);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          height: 360,
          decoration: BoxDecoration(
            color: const Color.fromARGB(255, 20, 25, 55),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                alignment: Alignment.center,
                height: 50,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    GestureDetector(
                      onTap: () {
                        Get.close(0);
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        width: 80,
                        alignment: Alignment.center,
                        child: Text("取消",
                            style: TextStyle(
                              color: const Color.fromARGB(255, 153, 153, 153),
                              fontSize: 16,
                            )),
                      ),
                    ),
                    Container(
                      alignment: Alignment.center,
                      child: Text(
                        widget.title ?? "选择周",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        Get.close(0);
                        widget.onConfirm?.call(weekDate!);
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        width: 80,
                        alignment: Alignment.center,
                        child: Text(
                          "确定",
                          style: TextStyle(),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: CupertinoPicker.builder(
                  scrollController: controller,
                  itemExtent: 44,
                  onSelectedItemChanged: (index) {
                    weekDate = weekList[index];
                    widget.onChanged?.call(weekDate);
                    setState(() {});
                  },
                  itemBuilder: (ctx, index) {
                    final model = weekList[index];
                    return Container(
                      alignment: Alignment.center,
                      child: Text(
                        model.description,
                        style: TextStyle(),
                      ),
                    );
                  },
                  childCount: weekList.length,
                ),
              ),
            ],
          ),
        )
      ],
    );
  }

  Future<List<LYWeekDate>> makeWeekData() async {
    List<LYWeekDate> result = [];
    DateTime now = DateTime.now();
    for (int i = 0; i < widget.maxWeekNumber; i++) {
      final startOfWeek = getStartOfWeek(now.subtract(Duration(days: 7 * i)));
      final endOfWeek = getEndOfWeek(now.subtract(Duration(days: 7 * i)));
      result.add(LYWeekDate(start: startOfWeek, end: endOfWeek));
    }
    return result;
  }
}
